module    CommonHelper

  # 返回当前登录的用户(如果有的话)
  def current_user
=begin
    if session[:user_id]
      @current_user ||= User.find_by(id: session[:user_id])
    elsif cookies.signed[:user_id]
      user = User.find_by(id: cookies.signed[:user_id])
      if user && user.authenticated?(cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
=end
    if cookies.signed[:user_id]
      user = User.find_by(id: cookies.signed[:user_id])
      if user && user.authenticated?(cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end

  end

  # 登入指定的用户
  def log_in(user)
    session[:user_id] = user.id
  end

  # 如果指定用户是当前用户,返回 true
  def current_user?(user)
    user == current_user
  end

  # 验证用户是否登录
   def user_login_in?
     !current_user.nil?
   end
  # 在持久会话中记住用户
  def remember(user)
    user.remember
    cookies.permanent.signed[:user_id] = user.id
    cookies.permanent[:remember_token] = user.remember_token
  end

  #验证是否为超管
  def admin?
    #是否登录
    current_admin
    #是否是管理员
    if @current_user.admin || current_user?(@user)
      @current_user
    else
      redirect_to root_path
    end
  end

end
